package http;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class HttpClient {
    private Socket socket;
    private String ip;
    private int port;
    public HttpClient(String ip,int port) throws IOException {
        this.ip=ip;
        this.port=port;
        socket=new Socket(ip,port);
    }
    public String get(String url) throws IOException {
        StringBuilder request=new StringBuilder();
        request.append("GET "+url+" HTTP/1.1\n");
        request.append("Host: "+ip+":"+port+"\n");
        request.append("\n");
        OutputStream outputStream=socket.getOutputStream();
        outputStream.write(request.toString().getBytes());
//        outputStream.flush();
        InputStream inputStream=socket.getInputStream();
        byte[] buffer=new byte[1024*1024];
        int n=inputStream.read(buffer);
        return new String(buffer,0,n,"utf-8");
    }
    public String post(String url,String body) throws IOException {
        StringBuilder request=new StringBuilder();
        request.append("POST "+url+" HTTP/1.1\n");
        request.append("Host: "+ip+":"+port+"\n");
        request.append("Content-Type: text/plain\n");
        request.append("Content-Length: "+body.getBytes().length+"\n");
        request.append("\n");
        request.append(body);
        OutputStream outputStream=socket.getOutputStream();
        outputStream.write(request.toString().getBytes());
//        outputStream.flush();
        InputStream inputStream=socket.getInputStream();
        byte[] buffer=new byte[1024*1024];
        int n=inputStream.read(buffer);
        return new String(buffer,0,n,"utf-8");
    }
    public static void main(String[] args) throws IOException {
        HttpClient httpClient=new HttpClient("42.192.83.143",8089);
//        String resp=httpClient.get("/AjaxMockServer/info");
//        System.out.println(resp);
        String resp=httpClient.post("/AjaxMockServer/info","这是正文");
        System.out.println(resp);
    }
}
